import type { CSDNElements } from '../../../../../../types/constants'
import type {
  EditorSelectorConfig,
  ThemeFutureOptions,
  ThemeType,
} from '../../../../../../types/interfaces'
import { BlogThemeService } from '../../../../../../lib/abstract'
import { ICON_IDS } from '../../../../../../lib/icons/types/constants'
import { CSDN_ARTICLE_TOC_SELECTOR } from '../../../../../../lib/page_handler/platform/csdn/types'
import {
  AppStyleCollections,
  BODY_SELECTOR,
  BodyAttrs,
  generateHideSelector,
  PLATFORM_PAGE_TYPES,
  PROJECT_PREFIX,
  SUPPORTED_PLATFORMS,
} from '../../../../../../types/constants'

export class CSDNThemeService extends BlogThemeService {
  readonly name = 'csdnTheme'
  readonly platformPageType: string = PLATFORM_PAGE_TYPES.BLOG.value
  private static instance: CSDNThemeService
  declare readonly elements: CSDNElements
  readonly editorClassNames: EditorSelectorConfig = {
    richTextEditor: '.htmledit_views',
    markdownEditor: '.markdown_views',
  }

  readonly futureOptions: ThemeFutureOptions = {
    copyRightButton: true,
  }

  readonly wrapperSelector: string = `${BODY_SELECTOR} #mainBox main`
  readonly excludedTitleElementsSelectors: string[] = [CSDN_ARTICLE_TOC_SELECTOR]
  readonly vipClassName = 'vip-name'

  constructor() {
    super(SUPPORTED_PLATFORMS.CSDN)

    this.checkEnv()
    this.initExcludedTitleElementsSelectors(this.excludedTitleElementsSelectors)
    this.updateElementStylesForTheme()
  }

  /**
   * 获取单例实例
   */
  static getInstance(): CSDNThemeService {
    if (!CSDNThemeService.instance) {
      CSDNThemeService.instance = new CSDNThemeService()
    }
    return CSDNThemeService.instance
  }

  updateElementStylesForTheme(): void {
    super.updateElementStylesForTheme()

    // 去掉富文本编辑器模式下的文本内容的颜色设置
    $(`${this.articleSelector} ${this.editorClassNames.richTextEditor} p span`).css('color', '')
  }

  platformStyleVar(theme: ThemeType): string {
    return `
/* 活动挑战 */
--${PROJECT_PREFIX}-theme-activity-text: ${this.getColorValue(theme, 'activityText')};
--${PROJECT_PREFIX}-theme-activity-bg: ${this.getColorValue(theme, 'activityBg')};
--${PROJECT_PREFIX}-theme-activity-shadow: ${this.getColorValue(theme, 'activityShadow')};
--${PROJECT_PREFIX}-theme-activity-shadow-hover: ${this.getColorValue(theme, 'activityShadowHover')};
--${PROJECT_PREFIX}-theme-activity-shadow-active: ${this.getColorValue(theme, 'activityShadowActive')};
/* 资源下载按钮 */
--${PROJECT_PREFIX}-theme-resource-download-btn-text: ${this.getColorValue(theme, 'resourceDownloadBtnText')};
`
  }

  getPageStyles(_theme: ThemeType): string {
    return `
${BODY_SELECTOR} {
  background-color: var(--${PROJECT_PREFIX}-theme-bg-base) !important;
}
/* 没有页眉时移除文章上边距 */
${BODY_SELECTOR}:has(${generateHideSelector('> #toolbarBox')}) .main_father {
  padding-top: 0 !important;
}
/* 解决隐藏元素后文章未居中的问题 */
${BODY_SELECTOR} #mainBox {
  width: auto !important;
  margin: 0  auto !important;
}
`
  }

  getMainStyles(theme: ThemeType): string {
    const {
      ARTICLE_CONTAINER,
    } = this.elements

    return `
${ARTICLE_CONTAINER.selector} .runner-box {
  color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
}
${this.getCopyrightButtonStyles(theme)}
${this.getActivityChallengeStyles(theme)}
${this.getResourceDownloadStyles(theme)}
`
  }

  getPatchedStyles(_theme: ThemeType): string {
    const { META_CONTAINER } = this.elements

    if (!META_CONTAINER || META_CONTAINER.selector === '') {
      return ''
    }

    return `
${META_CONTAINER.selector} {
  /* 解决信息栏和标签栏的间距问题 */
  .blog-tags-box {
    margin-top: 8px !important;
  }
}

/* 解决隐藏部分元素后，文章底部存在空白的问题 */
#toolBarBox:has(.left-toolbox.${AppStyleCollections.Hide.AD}, .left-toolbox[${BodyAttrs.HIDE_TYPE}]) {
  margin-bottom: 0 !important;
}
.blog-footer-bottom:has(#csdn-copyright-footer.${AppStyleCollections.Hide.AD}, #csdn-copyright-footer[${BodyAttrs.HIDE_TYPE}]) {
  margin-top: 0 !important;
}
`
  }

  getFixedStyles(_theme: ThemeType): string {
    const { ARTICLE_CONTAINER } = this.elements

    if (!ARTICLE_CONTAINER || ARTICLE_CONTAINER.selector === '') {
      return ''
    }

    return `
${ARTICLE_CONTAINER.selector} {  
  /* 解决代码块未超过容器宽度，但出现横向滚动条的问题 */
  .hide-preCode-box {
    margin: unset !important;
    background: var(--${PROJECT_PREFIX}-theme-code-hide-bg) !important;
  }
}
`
  }

  getAuthorStyles(_theme: ThemeType): string {
    const { ARTICLE_AUTHOR } = this.elements

    if (!ARTICLE_AUTHOR || ARTICLE_AUTHOR.selector === '') {
      return ''
    }

    return `
${ARTICLE_AUTHOR.selector} {
  display: inline-flex !important;
  align-items: center;
  justify-content: center;
  text-decoration: none !important;
  position: relative;
  
  /* 作者图标 */
  &::before {
    content: "";
    display: inline-block;
    width: 16px;
    height: 16px;
    margin-right: 6px;
    background-image: var(${this.themeVarService.generateIcon(ICON_IDS.role.author)});
    background-size: contain;
  }
  
  /* VIP 图标 */
  &.${this.vipClassName}::before {
    background-image: var(${this.themeVarService.generateIcon(ICON_IDS.role.vipUser)}) !important;
  }
  
  &:not(.${this.vipClassName}) {
    color: var(--${PROJECT_PREFIX}-theme-text-primary) !important;
  }
  
  &.${this.vipClassName} {
    position: relative;
    overflow: hidden;
    color: #2f1c0a !important;
    padding: 0 8px;
    z-index: 1;
    border-radius: 8px;
    box-shadow: var(--${PROJECT_PREFIX}-theme-author-shadow) !important;
    
    &::after {
      content: "";
      position: absolute;
      top: 0;
      left: -100%;
      width: 200%;
      height: 100%;
      background: var(--${PROJECT_PREFIX}-theme-author-bg) !important;
      z-index: -1;
      animation: vip-glow 2.5s linear infinite;
    }
  }
}
`
  }

  customPreInnerStyles(_theme: ThemeType): string {
    return `
/* 只对类型二生效：复制按钮悬浮在代码块中 */
code .hljs-button {
  background-color: var(--${PROJECT_PREFIX}-theme-code-toolbar-bg) !important;
}
.hljs-button {
  background-image: none !important;
  
  &::before {
    content: '';
    position: absolute;
    left: 5px;
    top: 50%;
    transform: translateY(-50%);
    width: 1.1em;
    height: 1.1em;
    background-image: var(${this.themeVarService.generateIcon(ICON_IDS.action.copy)});
    background-size: contain;
  }
  
  &::after {
    margin-left: 5px;
  }
}

.code-run-btn {
  background-image: var(${this.themeVarService.generateIcon(ICON_IDS.action.run)});
  background-repeat: no-repeat !important;
}
`
  }

  customPreOuterStyles(_theme: ThemeType): string {
    return `
.code-runner-container {
  background-color: var(--${PROJECT_PREFIX}-theme-bg-base) !important;

  .code-runner-box {
    border: none !important;
    .runner-result-title {
      color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
    }
  }
}
`
  }

  customImageStyles(_theme: ThemeType): string {
    return `
/* 显式重置 img 样式 */
.hide-preCode-box img {
  display: unset !important;
  margin: initial !important;
  filter: none !important;
}
`
  }

  getActivityChallengeStyles(_theme: ThemeType): string {
    const { ACTIVITY_CHALLENGE } = this.elements

    if (!ACTIVITY_CHALLENGE || ACTIVITY_CHALLENGE.selector === '') {
      return ''
    }

    return `
${ACTIVITY_CHALLENGE.selector} {
  /* 基础布局 */
  display: inline-block !important;
  padding: 6px 12px !important;
  width: auto;
  
  /* 文字样式 */
  font-size: 16px !important;
  font-weight: 600 !important;
  color: var(--${PROJECT_PREFIX}-theme-activity-text) !important;
  text-decoration: none !important;
  text-align: center;
  letter-spacing: 0.5px;
  
  /* 背景与边框 */
  border-radius: 8px;
  border: none;
  background: var(--${PROJECT_PREFIX}-theme-activity-bg) !important;
  box-shadow: var(--${PROJECT_PREFIX}-theme-activity-shadow);
    
  /* 交互效果 */
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  transform: translateY(0);
  
  /* 微光效果 */
  position: relative;
  overflow: hidden;
  
  &::after {
    content: "";
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: linear-gradient(
      to bottom right,
      rgba(255, 255, 255, 0) 0%,
      rgba(255, 255, 255, 0.1) 50%,
      rgba(255, 255, 255, 0) 100%
    );
    transform: rotate(30deg);
    z-index: 1;
  }

  /* 悬浮状态 */
  &:hover {
    transform: translateY(-2px);
    box-shadow: var(--${PROJECT_PREFIX}-theme-activity-shadow-hover);
    color: #fff !important;
    
    &::after {
      animation: shine 1.5s ease infinite;
    }
  }

  /* 点击状态 */
  &:active {
    transform: translateY(1px);
    box-shadow: var(--${PROJECT_PREFIX}-theme-activity-shadow-active);
  }
}
`
  }

  getResourceDownloadStyles(theme: ThemeType): string {
    const { RESOURCE_DOWNLOAD } = this.elements

    if (!RESOURCE_DOWNLOAD || RESOURCE_DOWNLOAD.selector === '') {
      return ''
    }

    return `
${RESOURCE_DOWNLOAD.selector} {
  display: flex !important;
  align-items: center;
  padding: 16px;
  background-color: var(--${PROJECT_PREFIX}-theme-bg-surface) !important;
  border-radius: 12px;
  box-shadow: var(--${PROJECT_PREFIX}-theme-shadow-sm) !important;
  border: 1px solid var(--${PROJECT_PREFIX}-theme-border-primary) !important;

  .file-icon {
    ${theme === 'dark' ? 'filter: brightness(0.8) contrast(1.1);' : ''}
  }

  .title {
    font-size: 16px;
    font-weight: 600;
    color: var(--${PROJECT_PREFIX}-theme-text-primary) !important;
    margin: 0 0 4px 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .desc {
    font-size: 14px;
    color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
    margin: 0;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 1.5;
  }

  .opt-box {
    flex: 0 0 auto;
    margin-left: 16px;
  }

  .btn-resource-link {
    display: inline-flex !important;
    align-items: center;
    justify-content: center;
    padding: 8px 16px;
    background-color: var(--${PROJECT_PREFIX}-theme-primary) !important;
    color: var(--${PROJECT_PREFIX}-theme-resource-download-btn-text) !important;
    border-radius: 15px;
    font-size: 14px;
    font-weight: 500;
    text-decoration: none;
    white-space: nowrap;

    &:hover {
      background-color: var(--${PROJECT_PREFIX}-theme-hover-primary) !important;
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
    }
  }
}
`
  }

  getGanttStyles(_theme: ThemeType): string {
    return `
/* 主标题 */
.titleText {
  fill: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
  font-size: 18px;
  text-anchor: middle;
}

/* 网格系统 */
.grid {
  .domain {
    stroke: var(--${PROJECT_PREFIX}-gantt-bg) !important;
  }
  .tick {
    /* 刻度线 */
    line {
      stroke: var(--${PROJECT_PREFIX}-gantt-line-border) !important;
    }
    /* 刻度文本 */
    text {
      fill: var(--${PROJECT_PREFIX}-gantt-text) !important;
    }
  }
}

/* 任务区块 */
.task {
  &.done0 {
    fill: var(--${PROJECT_PREFIX}-gantt-done-bg) !important;
    stroke: var(--${PROJECT_PREFIX}-gantt-done-border) !important;
  }
  &.active0 {
    fill: var(--${PROJECT_PREFIX}-gantt-active-bg) !important;
    stroke: var(--${PROJECT_PREFIX}-gantt-active-border) !important;
  }
  &.task0 {
    fill: var(--${PROJECT_PREFIX}-gantt-task-bg) !important;
    stroke: var(--${PROJECT_PREFIX}-gantt-task-border) !important;
  }
}

/* 任务文本 */
.taskText {
  &.doneText0 {
    fill: var(--${PROJECT_PREFIX}-gantt-done-text) !important;
  }
  &.activeText0 {
    fill: var(--${PROJECT_PREFIX}-gantt-active-text) !important;
  }
  &:not(.doneText0):not(.activeText0) {
    fill: var(--${PROJECT_PREFIX}-gantt-task-text) !important;
  }
}

/* 分区样式 */
.section {
  fill: var(--${PROJECT_PREFIX}-gantt-bg) !important;
}

/* 分区标题 */
.sectionTitle {
  fill: var(--${PROJECT_PREFIX}-gantt-text) !important;
}

/* 今日线 */
.today {
  stroke: var(--${PROJECT_PREFIX}-gantt-today-border) !important;
  stroke-width: 2px;
}
`
  }

  getSequenceDiagramStyles(_theme: ThemeType): string {
    return `
/* 参与者 */
line[id^="actor"] {
  stroke: var(--${PROJECT_PREFIX}-sequence-line-border) !important;
  fill: var(--${PROJECT_PREFIX}-sequence-line-text) !important;
  stroke-width: 2px !important;
}
rect.actor {
  fill: var(--${PROJECT_PREFIX}-sequence-actor-bg) !important;
  stroke: var(--${PROJECT_PREFIX}-sequence-actor-border) !important;
  stroke-width: 1.2px;
  rx: 6px !important;
  transition: all 0.3s ease;
  filter: drop-shadow(0 1px 2px rgba(0,0,0,0.05));
  
  &:hover {
    stroke-width: 2px;
    filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
  }
}
text.actor > tspan {
  fill: var(--${PROJECT_PREFIX}-sequence-actor-text) !important;
  stroke: none !important;
  font-size: 0.9em !important;
  font-weight: 500 !important;
  paint-order: stroke !important;
}

/* 消息 */
.messageLine0 {
  stroke: var(--${PROJECT_PREFIX}-sequence-message-border-0) !important;
}
.messageLine1 {
  stroke: var(--${PROJECT_PREFIX}-sequence-message-border-1) !important;
}
.messageText {
  fill: var(--${PROJECT_PREFIX}-sequence-message-text);
  stroke: none !important;
  font-size: 0.85em !important;
}

/* 注释 */
.note {
  fill: var(--${PROJECT_PREFIX}-sequence-note-bg) !important;
  stroke: var(--${PROJECT_PREFIX}-sequence-note-border) !important;
  stroke-width: 1.5px !important;
  stroke-dasharray: 5,2;
  rx: 8px !important;
  ry: 8px !important;
}
.noteText > tspan {
  fill: var(--${PROJECT_PREFIX}-sequence-note-text) !important;
  font-size: 0.8em !important;
  font-style: italic !important;
}
`
  }

  getLrGraphStyles(_theme: ThemeType): string {
    return `
/* ========== 核心节点 ========== */
.nodes .node {
  /* 基础形状 */
  rect, circle, polygon {
    fill: var(--${PROJECT_PREFIX}-lr-bg);
    stroke: var(--${PROJECT_PREFIX}-lr-border);
    stroke-width: 1.5px;
    transition: all 0.3s ease;
    rx: 4px;
  }

  /* 文字 */
  .label  {
    color: var(--${PROJECT_PREFIX}-lr-text);
    font-size: 0.9em;
    font-weight: 500;
  }

  /* 悬停效果 */
  &:hover {
    rect, circle, polygon {
      stroke-width: 2.5px;
      filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
    }
  }
}

/* ========== 连接线 ========== */
.edgePath {
  path {
    stroke: var(--${PROJECT_PREFIX}-lr-line-bg) !important;
    stroke-width: 1.5px;
    stroke-linecap: round;
  }
}

/* 连线文字 */
.edgeLabel {
  rect {
    fill: none;
  }
  span {
    font-size: 0.8em;
    background: var(--${PROJECT_PREFIX}-label-bg);
    color: var(--${PROJECT_PREFIX}-label-text);
  }
}
`
  }

  getFlowChartStyles(_theme: ThemeType): string {
    return `
&.flow-chart {    
  /* ========== 节点样式 ========== */
  /* 开始/结束节点（圆角矩形） */
  .flowchart#st, .flowchart#e {
    fill: var(--${PROJECT_PREFIX}-flow-start-end-bg) !important;
    stroke: var(--${PROJECT_PREFIX}-flow-start-end-border) !important;
    stroke-width: 1.5px;
  }
  
  /* 操作节点（矩形） */
  .flowchart#op {
    fill: var(--${PROJECT_PREFIX}-flow-op-bg) !important;
    stroke: var(--${PROJECT_PREFIX}-flow-op-border) !important;
    stroke-width: 1.2px;
  }
  
  /* 条件节点（菱形） */
  .flowchart#cond {
    fill: var(--${PROJECT_PREFIX}-flow-cond-bg) !important;
    stroke: var(--${PROJECT_PREFIX}-flow-cond-border) !important;
    stroke-width: 1.5px;
  }
  
  /* ========== 节点文字 ========== */
  .flowchartt {
    fill: var(--${PROJECT_PREFIX}-flow-text) !important;
    font-size: 14px !important;
    font-weight: 500 !important;
  }
  
  /* ========== 连接线 ========== */
  path[marker-end] {
    stroke: var(--${PROJECT_PREFIX}-flow-line-border);
    stroke-width: 1.5px;
    stroke-linecap: round;
  }
  
  /* 连接线文字 */
  text:not(.flowchartt) {
    fill: var(--${PROJECT_PREFIX}-flow-line-text);
    font-size: 12px;
    font-style: italic;
  }
}
`
  }
}
